//
//  GZOauthViewController.swift
//  sinaweibo
//
//  Created by mac book pro on 16/3/21.
//  Copyright © 2016年 finish. All rights reserved.
//

import UIKit
import SVProgressHUD
class GZOauthViewController: UIViewController,UIWebViewDelegate {
    override func loadView() {
        view = webView
        webView.delegate = self
        
    }
    override func viewDidLoad() {
        setupView()
        //开启加载提示
        SVProgressHUD.showWithStatus("正在加载!", maskType: SVProgressHUDMaskType.Black)
        
        let urlString = "\(sinaoath2api)?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url: NSURL? = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }
    /**
    初始化view
    */
    private func setupView(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "fillButtonClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelButtonClick")
    }
    
    
    
    // MARK: - 按钮点击事件
    @objc private func cancelButtonClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func fillButtonClick(){
        let js = "document.getElementById('userId').value='18316026526';document.getElementById('passwd').value"+"='w5505235w'"
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    // MARK: - 懒加载
    private lazy var webView = UIWebView()
    
}
extension GZOauthViewController{
    // MARK: － UIWebViewDelegate
    func webViewDidFinishLoad(webView: UIWebView){
        //加载完成,隐藏提示
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //request:Optional("http://www.baidu.com/?code=4eb3b01e53d36a6f8ed6cb58a3460627")
        let urlStr = request.URL?.absoluteString
        if (urlStr == nil || (urlStr!.hasPrefix(redirect_uri) == false) )  {
            return true
        }else{
            let conditon = "code="
            let queryStr = request.URL?.query
            if let query = queryStr{
                // 授权成功
                //截取code
                let queryNS = query as NSString
                let code =  queryNS.substringFromIndex(conditon.characters.count) as String
                GZUserAccountViewModel.sharedInstance.loadAccessToken(code, compication: { (error) -> () in
                    if error == nil{
                        SVProgressHUD.showSuccessWithStatus("加载Token成功!")
                        dispatch_after((dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                            AppDelegate.switchRootViewController(GZWelcomeViewController())
                            self.close()
                        })

                        
                    }else{
                        SVProgressHUD.showErrorWithStatus("请求获取Token失败!")
                        dispatch_after((dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    }
                })
                
            }else{
                //取消授权
                close()
            }
        }
        
        return false
    }
    func close(){
        SVProgressHUD.dismiss()
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
}

